<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="在Java的世界中，新开一个线程很容易，你只需要用下面的代码。 12Thread thread &#x3D; new Thread(() -&gt; &amp;#123;while(true) &amp;#123;doSomeThing...&amp;#125;&amp;#125;);thread.run(); 在深入一点，你应该知道Thread.run()调用了Linux的fork()函数，从父线程中copy出一个一摸一样的子线程，然后">
<meta property="og:type" content="article">
<meta property="og:title" content="换个角度看Java的Thread">
<meta property="og:url" content="https://guodh.gitee.io/blog/2018/12/22/2018/%E6%8D%A2%E4%B8%AA%E8%A7%92%E5%BA%A6%E7%9C%8BJava%E7%9A%84Thread/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="在Java的世界中，新开一个线程很容易，你只需要用下面的代码。 12Thread thread &#x3D; new Thread(() -&gt; &amp;#123;while(true) &amp;#123;doSomeThing...&amp;#125;&amp;#125;);thread.run(); 在深入一点，你应该知道Thread.run()调用了Linux的fork()函数，从父线程中copy出一个一摸一样的子线程，然后">
<meta property="og:locale">
<meta property="article:published_time" content="2018-12-22T09:18:18.000Z">
<meta property="article:modified_time" content="2019-01-05T04:07:25.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://guodh.gitee.io/blog/2018/12/22/2018/%E6%8D%A2%E4%B8%AA%E8%A7%92%E5%BA%A6%E7%9C%8BJava%E7%9A%84Thread/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>换个角度看Java的Thread | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2018/12/22/2018/%E6%8D%A2%E4%B8%AA%E8%A7%92%E5%BA%A6%E7%9C%8BJava%E7%9A%84Thread/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          换个角度看Java的Thread
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-12-22 17:18:18" itemprop="dateCreated datePublished" datetime="2018-12-22T17:18:18+08:00">2018-12-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2019-01-05 12:07:25" itemprop="dateModified" datetime="2019-01-05T12:07:25+08:00">2019-01-05</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在Java的世界中，新开一个线程很容易，你只需要用下面的代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Thread thread = <span class="keyword">new</span> Thread(() -&gt; &#123;<span class="keyword">while</span>(<span class="keyword">true</span>) &#123;doSomeThing...&#125;&#125;);</span><br><span class="line">thread.run();</span><br></pre></td></tr></table></figure>
<p>在深入一点，你应该知道Thread.run()调用了Linux的fork()函数，从父线程中copy出一个一摸一样的子线程，然后开出了一个新的线程。</p>
<p>但是呢？在深入思考一下，提一个问题：</p>
<blockquote>
<p>为啥说Go可以随意Goroutine几百几万个？而Java确不建议开那么多的线程，都是建议使用线程池来处理问题？或者说代码里面随意的使用new Thread()可以吗？</p>
</blockquote>
<p>答案就是: Go提供的线程是协程是语言层面的，线程切换不必牵涉CPU上下文切换（而且还提供了Forkjoin机制，当有单个协程阻塞，可以分配），Java的线程使用的是Linux的fork()，会涉及CPU上下文切换。</p>
<a id="more"></a>

<h2 id="关于协程"><a href="#关于协程" class="headerlink" title="关于协程"></a>关于协程</h2><p>关于Go的协程，更加细致的介绍可以看这两篇文章：<br><a href="https://blog.csdn.net/truexf/article/details/50510073">https://blog.csdn.net/truexf/article/details/50510073</a><br><a href="https://www.jianshu.com/p/533d58970397">https://www.jianshu.com/p/533d58970397</a></p>
<p>可以看到，由于Java的线程切换，涉及从用户态切换到内核态，多了一步操作。如果Java的线程过多就会造成CPU频繁上下文切换，浪费额外时间。所以，开发协程API对于语言来说还是有不小的价值。（是不是觉得Java有点弱，协程都不支持。）</p>
<p>因此在Java世界还是需要合理的使用线程，无论是GC线程还是业务线程。比较经典的例子就是，web服务器的线程池配置。当我们知道Java开了过多的线程之后反而会减低性能，那么我们的web服务器应该如何调优线程池配置？</p>
<p>以NIO模型为例，分为Accept、Selector、还有业务线程，这里的线程池该如何分配呢？</p>
<h3 id="NIO配置-Jetty"><a href="#NIO配置-Jetty" class="headerlink" title="NIO配置: Jetty"></a>NIO配置: Jetty</h3><p>全局使用一个线程池QueuedThreadPool,而最小线程数8最大200，Acceptor线程默认1个，Selector线程数默认2个</p>
<h3 id="NIO配置-undertow"><a href="#NIO配置-undertow" class="headerlink" title="NIO配置: undertow"></a>NIO配置: undertow</h3><p>undertow 配置的是 Acceptor 递归也就是线程数 1，IO worker是CPU核数，而工作线程数是CPU * 8;</p>
<blockquote>
<p>参考：<br><a href="https://www.cnblogs.com/maybo/p/7784687.html">https://www.cnblogs.com/maybo/p/7784687.html</a><br><a href="https://blog.csdn.net/rickiyeat/article/details/78906366">https://blog.csdn.net/rickiyeat/article/details/78906366</a></p>
</blockquote>
<h3 id="NIO配置-自己使用Netty来实现"><a href="#NIO配置-自己使用Netty来实现" class="headerlink" title="NIO配置: 自己使用Netty来实现"></a>NIO配置: 自己使用Netty来实现</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NettyHttpController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// accept 线程池，默认为1</span></span><br><span class="line">        EventLoopGroup boss = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">        <span class="comment">// selector 线程池，</span></span><br><span class="line">        EventLoopGroup worker = <span class="keyword">new</span> NioEventLoopGroup(Integer CPU_Num);</span><br><span class="line"></span><br><span class="line">        ServerBootstrap bootstrap = <span class="keyword">new</span> ServerBootstrap();</span><br><span class="line">        bootstrap.group(boss, worker);</span><br><span class="line">        bootstrap.channel(NioServerSocketChannel.class);</span><br><span class="line"></span><br><span class="line">        bootstrap.childHandler(<span class="keyword">new</span> ChannelInitializer&lt;Channel&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                ChannelPipeline channelPipeline = channel.pipeline();</span><br><span class="line">                </span><br><span class="line">                <span class="comment">// 业务线程池，伪代码，这里需要开发考虑</span></span><br><span class="line">                channel.add(<span class="keyword">new</span> Executor(() -&gt; &#123;</span><br><span class="line">                    doService();</span><br><span class="line">                    ....</span><br><span class="line">                    channel.respnse(<span class="string">&quot;调用成功&quot;</span>);</span><br><span class="line">                &#125;));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        ChannelFuture channelFuture = bootstrap.bind(<span class="number">9999</span>).sync();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> NettyHttpController().run();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="线程模型"><a href="#线程模型" class="headerlink" title="线程模型"></a>线程模型</h2><p>如果不考虑网络IO等因素，只考虑多线程业务系统的情况，又该如何处理线程池呢？是需要模仿NIO对线程进行分块处理还是怎么样呢？</p>
<p>在代码世界中，如果语言能力比不上人家，那么构建一个好的模型，同样能够击败对手。在《七周七并发》这本书中就推荐了7种并发模型。比较类似的，就是CSP模型（管道模型）和Actor模型，使用Go和Java分别能很好的实现这两者。</p>
<h3 id="CSP模型"><a href="#CSP模型" class="headerlink" title="CSP模型"></a>CSP模型</h3><ol>
<li>接收int 数组，并返回一个channel<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">gen</span><span class="params">(nums ...<span class="keyword">int</span>)</span> &lt;-<span class="title">chan</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    out := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">    <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">for</span> _, n := <span class="keyword">range</span> nums &#123;</span><br><span class="line">            out &lt;- n</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">close</span>(out)</span><br><span class="line">    &#125;()</span><br><span class="line">    <span class="keyword">return</span> out</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>从channel中接收数据，并进行2次方，并放到一个新的channel<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sq</span><span class="params">(in &lt;-<span class="keyword">chan</span> <span class="keyword">int</span>)</span> &lt;-<span class="title">chan</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    out := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">    <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">for</span> n := <span class="keyword">range</span> in &#123;</span><br><span class="line">            out &lt;- n * n</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">close</span>(out)</span><br><span class="line">    &#125;()</span><br><span class="line">    <span class="keyword">return</span> out</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>来看例子一: 如何使用刚刚的两个channel<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    c := gen(<span class="number">2</span>, <span class="number">3</span>)      <span class="comment">// 函数一</span></span><br><span class="line">    out := sq(c)        <span class="comment">// 函数二</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 消费输出结果</span></span><br><span class="line">    fmt.Println(&lt;-out) <span class="comment">// 4</span></span><br><span class="line">    fmt.Println(&lt;-out) <span class="comment">// 9</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>例子二: channel和Actor不同的是，channel关注channel，而不是接收消息的主体。因此，你还可以将一个channel发送给多个函数消费。<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    in := gen(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 启动两个 sq 实例，即两个goroutines处理 channel &quot;in&quot; 的数据</span></span><br><span class="line">    c1 := sq(in)</span><br><span class="line">    c2 := sq(in)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// merge 函数将 channel c1 和 c2 合并到一起，这段代码会消费 merge 的结果</span></span><br><span class="line">    <span class="keyword">for</span> n := <span class="keyword">range</span> merge(c1, c2) &#123;</span><br><span class="line">        fmt.Println(n) <span class="comment">// 打印 4 9, 或 9 4</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Actor模型"><a href="#Actor模型" class="headerlink" title="Actor模型"></a>Actor模型</h3></li>
</ol>
<p>不同于channel，Actor模型更加类似人类世界的交互模式。任何的交互都是异步的，都需要容忍失败。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Hello1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ActorSystem system = ActorSystem.create(<span class="string">&quot;actor-demo-java&quot;</span>);</span><br><span class="line">        ActorRef hello = system.actorOf(Props.create(Hello.class));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 需要定义接收者</span></span><br><span class="line">        hello.tell(<span class="string">&quot;Bob&quot;</span>, ActorRef.noSender());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 有一个线程单独处理，都是异步的，需要容忍失败</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123; <span class="comment">/* ignore */</span> &#125;</span><br><span class="line">        system.shutdown();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Hello</span> <span class="keyword">extends</span> <span class="title">UntypedActor</span> </span>&#123;</span><br><span class="line">    	</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(Object message)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (message <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;Hello &quot;</span> + message);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于我而言，Actor更类似于将消息系统引入到了单机业务中来，他更面向于各种复杂的情况。更类似一个完整的业务情况。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文从Java线程的实现，到NIO模式线程池配置，再到并发模型，来讲解了如何使用多线程。可以看到一个同步线程是最最简单，但是对于CPU而言，浪费类很多调度时间。如果对业务进行抽象，合理进行建模。无论是针对业务，还是针对系统性能，都能有很大的提升。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/Java/" rel="tag"># Java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/12/01/2018/%E9%87%8D%E6%96%B0%E8%AE%A4%E8%AF%86%E6%97%A5%E5%BF%97%E7%B3%BB%E7%BB%9F/" rel="prev" title="重新认识日志系统">
      <i class="fa fa-chevron-left"></i> 重新认识日志系统
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/12/29/2018/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9Fvs%E9%9B%86%E7%BE%A4%E7%B3%BB%E7%BB%9F/" rel="next" title="分布式系统vs集群系统">
      分布式系统vs集群系统 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E5%8D%8F%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">关于协程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#NIO%E9%85%8D%E7%BD%AE-Jetty"><span class="nav-number">1.1.</span> <span class="nav-text">NIO配置: Jetty</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NIO%E9%85%8D%E7%BD%AE-undertow"><span class="nav-number">1.2.</span> <span class="nav-text">NIO配置: undertow</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NIO%E9%85%8D%E7%BD%AE-%E8%87%AA%E5%B7%B1%E4%BD%BF%E7%94%A8Netty%E6%9D%A5%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.3.</span> <span class="nav-text">NIO配置: 自己使用Netty来实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E6%A8%A1%E5%9E%8B"><span class="nav-number">2.</span> <span class="nav-text">线程模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CSP%E6%A8%A1%E5%9E%8B"><span class="nav-number">2.1.</span> <span class="nav-text">CSP模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Actor%E6%A8%A1%E5%9E%8B"><span class="nav-number">2.2.</span> <span class="nav-text">Actor模型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
